package pers.qianyu.interceptor;

import cn.hutool.core.util.*;
import cn.hutool.json.*;
import lombok.extern.slf4j.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.web.servlet.*;
import pers.qianyu.constants.*;
import pers.qianyu.mapper.*;
import pers.qianyu.model.comm.*;
import pers.qianyu.model.entity.*;
import pers.qianyu.model.enums.*;
import pers.qianyu.utils.*;

import javax.servlet.http.*;
import java.io.*;
import java.util.*;

@Slf4j
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
        String token = req.getHeader(JwtConstants.TOKEN_HEADER);
        if (token == null || !token.startsWith(JwtConstants.TOKEN_PREFIX)) {
            retStr(res, "请先登录再进行访问");
            return false;
        }
        token = token.replace(JwtConstants.TOKEN_PREFIX, StrUtil.EMPTY);
        if (JwtTokenUtil.isTokenExpired(token)) {
            retStr(res, "您的token已过期");
            return false;
        }
        String subject = JwtTokenUtil.getSubject(token);
        UserPO userPO = userMapper.selectById(subject);
        String[] roles = Optional.ofNullable(userPO.getRoles())
                .map(r -> r.split(","))
                .orElse(new String[0]);
        if (!ArrayUtil.contains(roles, UserRole.ADMIN.getValue())) {
            retStr(res, "对不起，您没有权限访问该接口");
        }
        req.setAttribute("userId", subject);
        return true;
    }

    private void retStr(HttpServletResponse res, String msg) throws IOException {
        res.setContentType("application/json;charset=utf-8");
        res.setCharacterEncoding("utf-8");
        PrintWriter writer = res.getWriter();
        writer.write(JSONUtil.toJsonStr(Results.error(msg, null)));
        writer.flush();
        writer.close();
    }
}
